import 'package:agora_demo/setting.dart';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:agora_rtc_engine/agora_rtc_engine.dart' as prefix0;
import 'package:flutter/material.dart';

class VideoPage extends StatefulWidget {
  final String channelName;
  VideoPage({Key key, this.channelName}) : super(key: key);
  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> {
  List<int> list = [];
  bool isMute = false;
  bool isSpeaker = true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    list.clear();
    prefix0.AgoraRtcEngine.leaveChannel();
    AgoraRtcEngine.destroy();
    print("退出房间");
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initEngine();
  }
  //初始化引擎
  Future<void> initEngine() async{
    await AgoraRtcEngine.create(APP_ID);
    await AgoraRtcEngine.enableVideo();
    setAgoraListener();
    await AgoraRtcEngine.enableWebSdkInteroperability(true);
    await AgoraRtcEngine.setParameters(
        '''{\"che.video.lowBitRateStreamParameter\":{\"width\":320,\"height\":180,\"frameRate\":15,\"bitRate\":140}}''');
    await AgoraRtcEngine.joinChannel(Token, widget.channelName, null, 0);
  }
  //设置监听器
  setAgoraListener(){
    prefix0.AgoraRtcEngine.onError = (var code){
      print("有错误:$code");
    };
    //成功加入频道
    AgoraRtcEngine.onJoinChannelSuccess = (String channel,int uid,int elapsed){
      print("频道:$channel,ID:$uid,Elapsed:$elapsed");
    };
    //离开频道
    AgoraRtcEngine.onLeaveChannel = (){
      setState(() {
        list.clear();
      });
    };
    //有用户加入调用
    AgoraRtcEngine.onUserJoined = (int uid,int elapsed){
      print("$uid加入了房间");
      setState(() {
        list.add(uid);
      });
    };
    //有用户离开时调用
    AgoraRtcEngine.onUserOffline = (int uid,int elapsed){
      print("$uid离开了房间");
      setState(() {
        list.remove(uid);
      });
    };
  }
  //获取所有用户视图列表
  List<Widget> getUserView(){
    List<AgoraRenderWidget> views_list = [
      //先将自己的视图添加到第一个，preview控制是否预览画面
      AgoraRenderWidget(0,local: true,preview: true,)
    ];
    list.forEach((int uid){
      views_list.add(AgoraRenderWidget(uid));
    });
    return views_list;
  }
  //静音
  void mute(){
    setState(() {
      isMute = !isMute;
      AgoraRtcEngine.muteLocalAudioStream(isMute);
    });
  }
  //外放
  void speaker(){
    setState(() {
      setState(() {
        isSpeaker = !isSpeaker;
        AgoraRtcEngine.setEnableSpeakerphone(isSpeaker);
      });
    });
  }
  //切换摄像头
  void switchCamera(){
    AgoraRtcEngine.switchCamera();
  }
  //挂断
  void exit(){
    Navigator.pop(context);
  }
  @override
  Widget build(BuildContext context) {
    var userList = getUserView();
    return Scaffold(
      body: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          userList[0],
          otherView(userList),
          navButton(),
          bottomButton(),
        ],
      ),
    );
  }
  otherView(var userList){
    if(userList.length>1){
      return Positioned(
        top: MediaQuery.of(context).padding.top+15,
        right: 15,
        child: Container(
          height: 72,
          width: 80,
          child: userList[1],
        ),
      );
    }
    return Container();
  }
  navButton(){
    return Positioned(
      top: MediaQuery.of(context).padding.top+15,
      left: 15,
      child: InkWell(
        splashColor: Colors.transparent,
        child: Icon(Icons.arrow_back_ios),
        onTap: (){
          Navigator.pop(context);
        },
      ),
    );
  }
  bottomButton(){
    return Positioned(
      bottom: 60,
      child:Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              RawMaterialButton(
                onPressed: exit,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Icon(Icons.phone,color: Colors.white,size: 30,),
                ),
                shape: CircleBorder(),
                fillColor: Colors.redAccent,
              ),
              RawMaterialButton(
                onPressed: mute,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Icon(isMute?Icons.mic_off:Icons.mic,color: isMute?Colors.white:Colors.blue,size: 30,),
                ),
                shape: CircleBorder(),
                fillColor: isMute?Colors.blue:Colors.white,
              ),
              RawMaterialButton(
                onPressed: speaker,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Icon(isSpeaker?Icons.leak_add:Icons.leak_remove,color: isSpeaker?Colors.white:Colors.blue,size: 30,),
                ),
                shape: CircleBorder(),
                fillColor: isSpeaker?Colors.blue:Colors.white,
              ),
              RawMaterialButton(
                onPressed: switchCamera,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Icon(Icons.switch_camera,color: Colors.blue,size: 30,),
                ),
                shape: CircleBorder(),
                fillColor: Colors.white,
              ),
            ],
          ),
    );
  }
  bottomButtons(){
    return Positioned(
      bottom: 60,
      child: Container(
        width: MediaQuery.of(context).size.width,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            FloatingActionButton(
              child: Icon(Icons.mic,color: Colors.blue,),
              backgroundColor: Colors.white,
              onPressed: (){print("JOJO");},
            ),
            FloatingActionButton(
              child: Icon(Icons.local_phone,),
              backgroundColor: Colors.redAccent,
              onPressed: (){},
            ),
            FloatingActionButton(
              child: Icon(Icons.leak_remove),
              onPressed: (){print("JOJO");},
            )
          ],
        ),
      ),
    );
  }
}
